package ai4games_tests.maths;

import game2dai.maths.Geometry2D;
import processing.core.PApplet;

public class WhichSideOfPlane extends PApplet  {

	final int IRAD = 5;
	float x0,y0,x1,y1,px,py;
	float midx, midy, nx, ny;
	float length;
	float[] ipoint = null;
	int side;

	public void setup(){
		size(400,300);
		smooth();
		cursor(CROSS);
		x0 = 83;
		y0 = height - 99;
		x1 = width - 118;
		y1 = 53;
		length = sqrt((x1 - x0)*(x1 - x0) + (y1 - y0)*(y1 - y0));
		// Get midpoint coordinates
		midx = (x0 + x1)/2;
		midy = (y0 + y1)/2;
		// Get normal vector values and scale for drawing
		// plane normal
		nx = 40*(y0 - y1) / length;
		ny = 40*(x1 - x0) / length;
		ellipseMode(RADIUS);
	}

	public void draw(){
		background(128);
		pushMatrix();
		px = mouseX;
		py = mouseY;
		// Two methods for calculating the side of the plane for a point
		// both give the same results so comment out one of these lines.
		//		side = Intersect.which_side_pp(x0, y0, x1, y1, px, py);
		side = Geometry2D.which_side_pn(x0, y0, nx, ny, px, py);

		drawArrow(x0, y0, x1, y1, 8, 2.0f, color(0,255,0));
		drawArrow(midx, midy, midx + nx, midy + ny, 6, 1.3f, color(0,255,255));

		noStroke();
		fill(255,255,0);
		switch(side){
		case Geometry2D.ON_PLANE:
			text("ON the plane", 10, height - 4);
			break;
		case Geometry2D.PLANE_OUTSIDE:
			text("OUTSIDE the plane", 10, height - 4);
			break;
		case Geometry2D.PLANE_INSIDE:
			text("INSIDE the plane", 10, height - 4);
			break;
		}
		popMatrix();
	}

	public void drawArrow(float x0, float y0, float x1, float y1, float headSize, float swidth, int col){
		// Draw arrow body
		fill(col);
		stroke(col);
		strokeWeight(swidth);
		line(x0,y0,x1,y1);
		// Now draw arrowhead
		noStroke();
		float angle = atan2(y1-y0, x1-x0);
		pushMatrix();
		translate(x1, y1);
		rotate(angle);
		beginShape(TRIANGLES);
		vertex(0, 0);
		vertex(-headSize, -headSize/2);
		vertex(-headSize, +headSize/2);
		endShape();
		popMatrix();
	}
}